package com.yozinga;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yozinga.database.yozingaDataBaseManager;
import com.yozinga.fragment.OfferDealPageFragment;
import com.yozinga.fragment.OfferDealPageFragment.TwitterShareListener;
import com.yozinga.twitter.AlertDialogManager;
import com.yozinga.twitter.ConnectionDetector;
import com.yozinga.util.SharedData;

public class OfferDealPage extends BaseActivity implements TwitterShareListener{
	String merchantId,offerId,CategoryId,merchantName,merchantTagLine,merchantLatitude,merchantLongitude;
	Bundle bundle;



	//Twitter
	static String TWITTER_CONSUMER_KEY = "zMKEV2waDWd44lJgR50CbQ"; // place your cosumer key here
	static String TWITTER_CONSUMER_SECRET = "KnmqjZ7VAM9YubkxZpMuK6ccfl75waEtcqPWP7bSo"; // place your consumer secret here

	// Shared Preference Constants
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
	static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	// Twitter oauth urls
	static final String URL_TWITTER_AUTH = "auth_url";
	static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	// Progress dialog bar 
	ProgressDialog pDialog;
	// Twitter Variables
	private static Twitter twitter;
	private static RequestToken requestToken;
	// Shared Preferences 
	private static SharedPreferences mSharedPreferences;
	// Internet Connection detector
	private ConnectionDetector cd;
	String verifier;
	SharedData sharedData;
	// Alert Dialog Manager
	AlertDialogManager alert = new AlertDialogManager();



	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_offer_dealpage);
		bundle = getIntent().getBundleExtra("merchantInfo");

		if(!bundle.getBoolean("favouriteOffer1")){
			((ImageView)findViewById(R.id.ivFavourite)).setOnClickListener(this);
			((ImageView)findViewById(R.id.ivFavourite)).setVisibility(View.VISIBLE);
		}
		merchantId = bundle.getString("merchantId");
		offerId = bundle.getString("offerId");
		CategoryId = bundle.getString("categoryId");
		merchantName = bundle.getString("merchantName");
		merchantTagLine = bundle.getString("merchantTagLine");
		Log.i("Today","Merchant TagLine"+merchantTagLine);

		merchantLatitude = bundle.getString("latitude");
		merchantLongitude = bundle.getString("longitude");

		TextView tvMerchantName = (TextView)findViewById(R.id.merchantName);
		tvMerchantName.setText(bundle.getString("merchantName"));

		OfferDealPageFragment offerDealPageFragment = new OfferDealPageFragment();
		offerDealPageFragment.setArguments(bundle);
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.replace(R.id.flFragmentHolder, offerDealPageFragment);
		transaction.commit();



		/*//Twitter
		cd = new ConnectionDetector(this);
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}
		// Check if twitter keys are set
		if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
			// Internet Connection is not present
			alert.showAlertDialog(this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
			// stop executing code by return
			return;
		}
		// Shared Preferences
		mSharedPreferences = this.getSharedPreferences("MyPref", 0);

		//This if conditions is tested once is redirected from twitter page. 
		// I am Parsing the uri to get oAuth Verifier

		if (!isTwitterLoggedInAlready()) {
			Uri uri = this.getIntent().getData();
			if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
				// oAuth verifier
				verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
				try {
					// Get the access token
					Log.i("NCS","Token  :"+verifier);
					Task task = new Task();
					task.execute();
				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
				}
			}
		}   */

	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.ivFavourite){
			Toast.makeText(getApplicationContext(), "Offer added to Favourites", Toast.LENGTH_LONG).show();
			ContentValues cv = new ContentValues();

			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANTID, merchantId);
			cv.put(yozingaDataBaseManager.Favourites.COL_OFFERID, offerId);
			cv.put(yozingaDataBaseManager.Favourites.COL_CATEGORYID, CategoryId);
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANTNAME, merchantName);
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_TAGLINE, merchantTagLine);
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_LATITUDE, merchantLatitude);
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_LONGITUDE, merchantLongitude);

			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_VIDEO_LINK, bundle.getString("merchantVideoLink"));
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_FULL_ADDRESS, bundle.getString("merchantFullAddress"));
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_PHONE_NUMBER, bundle.getString("merchantPhoneNumber"));
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_INFO, bundle.getString("merchantInfo"));
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_FACEBOOL_URL, bundle.getString("merchantFacebook"));
			cv.put(yozingaDataBaseManager.Favourites.COL_MERCHANT_TWITTER_URL, bundle.getString("merchantTwitter"));

			getContentResolver().insert(yozingaDataBaseManager.Favourites.FAVOURITE_CONTENT_URI, cv);
		}else{
			super.onClick(v);
		}
	}



	//Twitter
	class Task extends AsyncTask<Void, Void, AccessToken>{

		AccessToken accessToken;
		@Override
		protected AccessToken doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
				long userID = accessToken.getUserId();
				User user;
				try {
					user = twitter.showUser(userID);
					String username = user.getName();
					Log.e("UserID: ", "userID: "+userID+""+username);
					// Displaying in xml ui
					Log.v("Welcome:","Thanks:"+Html.fromHtml("<b>Welcome " + username + "</b>"));

				} catch (TwitterException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					Log.e("TwitterException OAuth Token", "> " + e1.getMessage());
				}
				Log.i("NCS","Accesss  :"+accessToken);
				// Shared Preferences
			} catch (TwitterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return accessToken;
		}

		@Override
		protected void onPostExecute(AccessToken result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Editor e = mSharedPreferences.edit();

			// After getting access token, access token secret
			// store them in application preferences
			e.putString(PREF_KEY_OAUTH_TOKEN, result.getToken());
			e.putString(PREF_KEY_OAUTH_SECRET,result.getTokenSecret());

			// Store login status - true
			e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
			e.commit(); // save changes

			Log.i("Twitter OAuth Token", "> " + result.getToken());

			// Hide login button
			//findViewById(R.id.button1).setVisibility(View.GONE);

			sendStatus("dealName"+"\n"+"dealTageLine");

			// Show Update Twitter
			/*findViewById(R.id.editText1).setVisibility(View.VISIBLE);
			findViewById(R.id.button2).setVisibility(View.VISIBLE);*/

			// Getting user details from twitter
			// For now i am getting his name only




		}

	}

	public void sendStatus(String status){
		new updateTwitterStatus().execute(status);
	}                                                     


	class Login  extends AsyncTask<Void, Void, RequestToken>{

		@Override
		protected RequestToken doInBackground(Void... params) {

			// Check if already logged in
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			twitter4j.conf.Configuration configuration = builder.build();

			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			try {
				requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
			} catch (TwitterException e) {
				e.printStackTrace();
			}


			return requestToken;
		}

		@Override
		protected void onPostExecute(RequestToken result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			checkLogin(result);
		}

	}

	public void checkLogin(RequestToken token){
		requestToken = token;
		this.startActivity(new Intent(Intent.ACTION_VIEW, 
				Uri.parse(requestToken.getAuthenticationURL())));
	}

	// Checking User is already logged or not by using Shared preferences 
	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
	}

	//Function to update status
	class updateTwitterStatus extends AsyncTask<String, String, String> {

		//Before starting background thread I am showing Progress Dialog 
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getApplicationContext());
			pDialog.setMessage("Updating to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			try {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
				builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
				// Access Token 
				String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
				// Access Token Secret
				String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

				// Update status
				twitter4j.Status response = twitter.updateStatus(status);

				Log.d("Status", "> " + response.getText());
			} catch (TwitterException e) {
				// Error in updating status
				Log.d("Twitter Update Error", e.getMessage());                
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog and show
		 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
		 * from background thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {

					Log.i("Today","Status tweeted successfully");
					Toast.makeText(getApplicationContext(),
							"Deal tweeted successfully", Toast.LENGTH_SHORT)
							.show();
					finish();
				}
			});
		}

	}

	@Override
	public void dealShare(String dealName, String dealTagLine) {
		if (!isTwitterLoggedInAlready()) {
			Login login = new Login();
			login.execute();
		} else {
			//sendStatus(sharedData.getTwitterStaus());
			sendStatus(dealName+"\n"+dealTagLine);
		}
	}	
}